//
//  PersonTableViewCell.m
//  SoundPill
//
//  Created by 宋旭东 on 15/6/10.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "PersonTableViewCell.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "AppDelegate.h"
#import "PersonView.h"
#import "JCAlertView.h"
@interface PersonTableViewCell ()
{
    
}
@property (strong, nonatomic) Musician *musicianInfo;
@property (strong, nonatomic) UIView *line;
@end

@implementation PersonTableViewCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    
    if (self) {
        // 创建子视图
        self.musicianInfo = [[Musician alloc] init];
        [self createSubviews];
//        self.pushDelegate = self;
    }
    return self;
}

- (void)createSubviews
{
    // 头像
    self.avatar = [[UIImageView alloc] initWithFrame:CGRectMake(15, 12, ([UIScreen mainScreen].bounds.size.height -45 -64) / 8 - 24, ([UIScreen mainScreen].bounds.size.height -45 -64) / 8 - 24)];
    self.avatar.userInteractionEnabled = YES;
    self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.avatar addGestureRecognizer:self.tap];
    [self.contentView addSubview:self.avatar];

    // 用户名
    self.userName = [[UILabel alloc] initWithFrame:CGRectMake(self.avatar.frame.origin.x + self.avatar.frame.size.width + 8, self.avatar.frame.origin.y, 150, 20)];
    [self.userName setFont:[UIFont fontWithName:@"Helvetica-Bold" size:15.0f]];
    [self.contentView addSubview:self.userName];
    
    // 签名
    self.introduce = [[UILabel alloc] initWithFrame:CGRectMake(self.userName.frame.origin.x, self.userName.frame.origin.y + self.userName.frame.size.height + 5, 200, 12)];
    [self.introduce setFont:[UIFont systemFontOfSize:14.0f]];
    [self.introduce setTextColor:[UIColor grayColor]];
    [self.contentView addSubview:self.introduce];

    // 关注按钮
    self.attention = [UIButton buttonWithType:UIButtonTypeCustom];
    if ([UIScreen  mainScreen].bounds.size.width > 375) {
        [self.attention setFrame:CGRectMake(self.frame.size.width, self.avatar.frame.origin.y - 2 , 25, 25)];
    } else {
        [self.attention setFrame:CGRectMake(self.frame.size.width - 40, self.avatar.frame.origin.y - 2 , 25, 25)];
    }
    [self.attention addTarget:self action:@selector(attention:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.attention];

    // 关系
    self.relation = [[UILabel alloc] initWithFrame:CGRectMake(self.attention.frame.origin.x - (_attention.frame.size.width / 2), self.attention.frame.origin.y + self.attention.frame.size.height, 30, 12)];
//    _relation.backgroundColor =[UIColor redColor];
    _relation.textAlignment = NSTextAlignmentCenter;
    [self.relation setFont:[UIFont fontWithName:@"Helvetica-Bold" size:10.0f]];
    [self.contentView addSubview:self.relation];
    
    self.line = [[UIView alloc] initWithFrame:CGRectZero];
    [self.contentView addSubview:_line];
}
- (void)layoutSubviews{
    [super layoutSubviews];
    _avatar.frame = CGRectMake(15, 12, ([UIScreen mainScreen].bounds.size.height -45 -64) / 8 - 24, ([UIScreen mainScreen].bounds.size.height -45 -64) / 8 - 24);
    _userName.frame = CGRectMake(self.avatar.frame.origin.x + self.avatar.frame.size.width + 8, self.avatar.frame.origin.y, [UIScreen mainScreen].bounds.size.width * 0.468, _avatar.frame.size.height / 2);
    _introduce.frame = CGRectMake(self.userName.frame.origin.x, _userName.frame.origin.y + _userName.frame.size.height + 3, [UIScreen mainScreen].bounds.size.width * 0.625, _avatar.frame.size.height / 2);
    if ([UIScreen  mainScreen].bounds.size.width > 375) {
        _attention.frame = CGRectMake(self.frame.size.width - 10 - ( _avatar.frame.size.height / 4 * 3), self.avatar.frame.origin.y , 25, 25);
        _relation.frame = CGRectMake(self.frame.size.width - 10 -  _avatar.frame.size.height, _avatar.frame.size.height / 2 + _avatar.frame.origin.y, _avatar.frame.size.width, _avatar.frame.size.height / 2);
    } else {
        _attention.frame = CGRectMake(self.frame.size.width - 7 - _avatar.frame.size.height / 4 * 3, self.avatar.frame.origin.y , 25,25);
        _relation.frame = CGRectMake(self.frame.size.width - 7 - _avatar.frame.size.height, _avatar.frame.size.height / 2 + _avatar.frame.origin.y, _avatar.frame.size.width, _avatar.frame.size.height / 2);
    }
    for (int i = 0; i < _musician.workCoverArr.count; i++) {
        // 作品封面
        if (i < 4) {
            self.workCover = [[WorkCover alloc] initWithFrame:CGRectMake(self.avatar.frame.origin.x + (([UIScreen mainScreen].bounds.size.width - 30 - 9) / 4 + 3) * i, _avatar.frame.origin.y + _avatar.frame.size.height + 10, ([UIScreen mainScreen].bounds.size.width - 30 - 9) / 4 , ([UIScreen mainScreen].bounds.size.width - 30 - 9) / 4)];
            [self.workCover.imageview setImageWithURL:[NSURL URLWithString:_musician.workCoverArr[i]] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
            NSString *workid = _musician.workidArr[i];
            _workCover.tag = workid.intValue;
            [self.workCover addTarget:self action:@selector(playWork:) forControlEvents:UIControlEventTouchUpInside];
            [self.contentView addSubview:self.workCover];
            
            // 作品名
            self.workName = [[UILabel alloc] initWithFrame:CGRectMake(_workCover.frame.origin.x, self.workCover.frame.origin.y + self.workCover.frame.size.height + 5, _workCover.frame.size.width, 20)];
            _workName.textAlignment = NSTextAlignmentLeft;
            [self.workName setTextColor:[UIColor blackColor]];
            [self.workName setFont:[UIFont systemFontOfSize:12.0f]];
            self.workName.text = _musician.workNameArr[i];
            [self.contentView addSubview:self.workName];
        }
    }
    [self.avatar setImageWithURL:[NSURL URLWithString:_musician.avatar] placeholderImage:nil];
    self.userName.text = _musician.userName;
    self.introduce.text = _musician.introduce;
    self.userId = _musician.userId;
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *udid = [user objectForKey:@"uid"];
    NSString *relationStr = [NSString stringWithFormat:@"%@", _musician.relation];
    self.attention.hidden = NO;
    self.relation.hidden = NO;
    if ([relationStr isEqualToString:@"0"]) {
        if ([self.userId isEqualToString:udid]) {
            self.attention.hidden = YES;
            self.relation.hidden = YES;
        }else{
            self.attention.userInteractionEnabled = YES;
            [self.attention setImage:[UIImage imageNamed:@"attention"] forState:UIControlStateNormal];
            self.relation.text = @"加关注";
        }
    }else if ([relationStr isEqualToString:@"1"]){
        self.attention.userInteractionEnabled = NO;
        [self.attention setImage:[UIImage imageNamed:@"didattention"] forState:UIControlStateNormal];
        self.relation.text = @"已关注";
    }else if ([relationStr isEqualToString:@"2"]){
        self.attention.userInteractionEnabled = NO;
        [self.attention setImage:[UIImage imageNamed:@"allattention"] forState:UIControlStateNormal];
        self.relation.text = @"相互关注";
    }
//    _line.frame = CGRectMake(0, self.frame.size.height, self.frame.size.width, 2);
//    _line.backgroundColor = [UIColor blackColor];//[UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000];
}
#pragma mark - 重写set方法
//- (void)setMusician:(Musician *)musician
//{
////    _musicianInfo = musician;x
//    
//}

#pragma mark -- 关注按钮的触发方法
- (void)attention:(UIButton *)sender
{
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] == nil) {
        //我的
        //提示请先登陆
        [JCAlertView showTwoButtonsWithTitle:@"未登录" Message:@"登录后才能继续操作" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"再看看" Click:^{

        } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"去登录" Click:^{
            [[AppDelegate shareDelegate] chooseRootViewController];
        }];

//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"未登录" message:@"登录后才能继续操作" delegate:self cancelButtonTitle:@"再看看" otherButtonTitles:nil];
//        alert.tag = 12345;
//        [alert addButtonWithTitle:@"去登录"];
//        [alert show];
    }else{
       [self requestAttention];
       [self.attention setImage:[UIImage imageNamed:@"关注2"] forState:UIControlStateNormal];
       self.relation.text = @"已关注";
    }
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (alertView.tag==12345){
        if (buttonIndex == 0) {
        }else if (buttonIndex == 1){
            //跳到登陆页
            [[AppDelegate shareDelegate] chooseRootViewController];
        }
    }
}

#pragma mark -- 点击用户头像的触发方法
- (void)tapAction:(UITapGestureRecognizer *)tap
{
//    NSLog(@"%@", self.nextResponder.nextResponder.nextResponder);
    PersonView *person = (PersonView *)self.nextResponder.nextResponder.nextResponder;
    UITableView *tableview = (UITableView *)self.nextResponder.nextResponder;
    NSIndexPath *index = [tableview indexPathForCell:self];
    person.index = index.row;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:_musician.userId forKey:@"othersUserID"];
    [userDefaults synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"findGotoUser" object:_musician.userId];
}

#pragma mark -- 点击作品封面的触发方法
- (void)playWork:(WorkCover *)sender{

//    NSLog(@"button.tag = %d", sender.tag);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoPlayer" object:[NSString stringWithFormat:@"%ld", sender.tag]];
}

#pragma mark -- 请求关系接口
- (void)requestAttention
{
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/follow", _userId];
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [netWorkManager stopMonitoring];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"find_reload" object:self];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}


@end
